import os
import logging
from time import strftime
from global_conf import config

class Log:
    def __init__(self,file_name):
        self.now = strftime("%Y-%m-%d-%H")
        self.log_name = os.path.join(config.log_path, '{0}.log'.format(self.now))
        self.file_name = file_name

    def __print_console(self, level, message):
        # 创建一个logger
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)
        # 创建一个handler，用于写入日志文件
        fh = logging.FileHandler(self.log_name, 'a', encoding='utf-8')
        fh.setLevel(logging.DEBUG)
        # 再创建一个handler，用于输出到控制台
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        # 定义handler的输出格式
        formatter = logging.Formatter(fmt=self.fmt)
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
        # 给logger添加handler
        logger.addHandler(fh)
        logger.addHandler(ch)
        # 记录一条日志
        if level == 'info':
            logger.info("[{0}] {1}".format(self.file_name,message))
        elif level == 'debug':
            logger.debug("[{0}] {1}".format(self.file_name, message))
        elif level == 'warning':
            logger.warning("[{0}] {1}".format(self.file_name, message))
        elif level == 'error':
            logger.error("[{0}] {1}".format(self.file_name, message))
        logger.removeHandler(ch)
        logger.removeHandler(fh)
        # 关闭打开的文件
        fh.close()

    @property
    def fmt(self):
        return '[%(asctime)-2s] [%(levelname)-2s] [%(lineno)-2s] %(message) s'

    def debug(self, message):
        self.__print_console('debug', message)

    def info(self, message):
        self.__print_console('info', message)

    def warning(self, message):
        self.__print_console('warning', message)

    def error(self, message):
        self.__print_console('error', message)
